package com.personal.website.lottery.web.controller.admin;

import com.personal.website.lottery.web.model.DoubleColorBall;
import com.personal.website.lottery.web.service.DoubleColorBallService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 10171225 on 2016/6/23.
 */
@Controller
@RequestMapping("/admin/doubleColorBallManage")
public class DoubleColorBallManageController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private DoubleColorBallService doubleColorBallService;

    @RequestMapping("/doubleColorBallSearch")
    public String doubleColorBallSearch(HttpServletRequest request, Model model) {
        String text = null;
        try {
            text = request.getParameter("text");
            text = URLDecoder.decode(text, "UTF-8");
            model.addAttribute("searchInput", text);
            model.addAttribute("doubleColorBallList",this.doubleColorBallService.getDoubleColorBallLikeIssue(Integer.parseInt(text.trim()), 50));
        } catch (NumberFormatException e) {
            logger.info(String.format("搜索期号为'%s'的双色球时，期号解析失败！", text), e);
        } catch (Exception e) {
            logger.error(String.format("搜索期号为'%s'的双色球记录时失败！", text), e);
        }
        return "admin/doubleColorBallManage";
    }

    @RequestMapping("/doubleColorBallEdit")
    public String doubleColorBallEdit(HttpServletRequest request, Model model) {
        int doubleColorBallId = -1;
        try {
            doubleColorBallId = Integer.parseInt(request.getParameter("doubleColorBallId"));
            DoubleColorBall doubleColorBall = this.doubleColorBallService.getBallById(doubleColorBallId);
            model.addAttribute("doubleColorBall", doubleColorBall);
        } catch (Exception e) {
            logger.error(String.format("未知异常，查找双色球失败！", doubleColorBallId), e);
        }
        return "admin/doubleColorBallManage/doubleColorBallEdit";
    }

    @RequestMapping("/doubleColorBallDelete")
    @ResponseBody
    public String doubleColorBallDelete(HttpServletRequest request) {
        int doubleColorBallId = -1;
        try {
            doubleColorBallId = Integer.parseInt(request.getParameter("doubleColorBallId"));
            DoubleColorBall doubleColorBall = this.doubleColorBallService.getBallById(doubleColorBallId);
            if (doubleColorBall == null) {
                logger.error(String.format("删除双色球'%d'时，双色球不存在！", doubleColorBallId));
                return "不存在该双色球！";
            }
            if (this.doubleColorBallService.deleteDoubleColorBall(doubleColorBallId)) {
                logger.info(String.format("删除双色球'%d'，删除成功！", doubleColorBallId));
                return "删除成功！";
            } else {
                logger.error(String.format("删除双色球'%d'，删除失败！", doubleColorBallId));
                return "删除失败！";
            }
        } catch (Exception e) {
            logger.error(String.format("未知异常，删除失败！", doubleColorBallId), e);
            return "删除失败！";
        }
    }

    @RequestMapping("/doubleColorBallEditSubmit")
    @ResponseBody
    public String doubleColorBallEditSubmit(HttpServletRequest request) {
        int issue = -1;
        try {
            String doubleColorBallId = URLDecoder.decode(request.getParameter("doubleColorBallId"), "UTF-8");
            String redOne = URLDecoder.decode(request.getParameter("redOne"), "UTF-8");
            String redTwo = URLDecoder.decode(request.getParameter("redTwo"), "UTF-8");
            String redThree = URLDecoder.decode(request.getParameter("redThree"), "UTF-8");
            String redFour = URLDecoder.decode(request.getParameter("redFour"), "UTF-8");
            String redFive = URLDecoder.decode(request.getParameter("redFive"), "UTF-8");
            String redSix = URLDecoder.decode(request.getParameter("redSix"), "UTF-8");
            String blue = URLDecoder.decode(request.getParameter("blue"), "UTF-8");
            String drawDate = URLDecoder.decode(request.getParameter("drawDate"), "UTF-8");
            String currentPrizePool = URLDecoder.decode(request.getParameter("currentPrizePool"), "UTF-8");
            String prizeInfo = URLDecoder.decode(request.getParameter("prizeInfo"), "UTF-8");

            DoubleColorBall doubleColorBall = this.doubleColorBallService.getBallById(Integer.parseInt(doubleColorBallId));

            doubleColorBall.setIssue(issue);
            doubleColorBall.setRedOne(redOne);
            doubleColorBall.setRedTwo(redTwo);
            doubleColorBall.setRedThree(redThree);
            doubleColorBall.setRedFour(redFour);
            doubleColorBall.setRedFive(redFive);
            doubleColorBall.setRedSix(redSix);
            doubleColorBall.setBlue(blue);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            doubleColorBall.setDrawDate(sdf.parse(drawDate));
            doubleColorBall.setCurrentPrizePool(currentPrizePool);
            doubleColorBall.setPrizeInfo(prizeInfo);

            if (this.doubleColorBallService.updateDoubleColorBall(doubleColorBall)) {
                logger.info(String.format("编辑期号为'%s'的双色球，编辑成功！", issue));
                return "编辑成功！";
            } else {
                logger.error(String.format("编辑期号为'%s'的双色球，提交失败！", issue));
                return "编辑失败！";
            }

        } catch (Exception e) {
            logger.error(String.format("编辑期号为'%s'的双色球，提交失败！", issue), e);
            return "编辑失败！";
        }
    }

    @RequestMapping("/doubleColorBallCreate")
    @ResponseBody
    public String doubleColorBallCreate(HttpServletRequest request) {
        String doubleColorBalls = request.getParameter("doubleColorBalls");
        String failedRecord = "";
        for(String doubleColorBall : doubleColorBalls.split(";")) {
            try {
                Pattern p = Pattern.compile("'[^']*'");
                Matcher m = p.matcher(doubleColorBall);
                List<String> fieldList = new ArrayList<String>();
                while(m.find()){
                    fieldList.add(m.group());
                }
                if(createSingleBallRecord(fieldList)) {
                    logger.info(String.format("双色球记录(%s)插入成功!", doubleColorBall));
                } else {
                    failedRecord += doubleColorBall;
                    logger.info(String.format("双色球记录(%s)插入失败！", doubleColorBall));
                }
            } catch (Exception e) {
                failedRecord += doubleColorBall;
                logger.error(String.format("双色球记录(%s)插入失败！", doubleColorBall), e);
            }
        }
        if("".equals(failedRecord)) {
            return "导入成功！";
        } else {
            return "导入过程中导入失败记录如下：\n" + failedRecord;
        }
    }

    private boolean createSingleBallRecord(List<String> fieldList) throws Exception {
        if (fieldList.size() != 11) {
            return false;
        }
        DoubleColorBall doubleColorBall = new DoubleColorBall();
        doubleColorBall.setIssue(Integer.parseInt(trimSingleQuote(fieldList.get(0))));
        doubleColorBall.setRedOne(trimSingleQuote(fieldList.get(1)));
        doubleColorBall.setRedTwo(trimSingleQuote(fieldList.get(2)));
        doubleColorBall.setRedThree(trimSingleQuote(fieldList.get(3)));
        doubleColorBall.setRedFour(trimSingleQuote(fieldList.get(4)));
        doubleColorBall.setRedFive(trimSingleQuote(fieldList.get(5)));
        doubleColorBall.setRedSix(trimSingleQuote(fieldList.get(6)));
        doubleColorBall.setBlue(trimSingleQuote(fieldList.get(7)));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        doubleColorBall.setDrawDate(sdf.parse(trimSingleQuote(fieldList.get(8))));
        doubleColorBall.setPrizeInfo(trimSingleQuote(fieldList.get(9)));
        doubleColorBall.setPrizeInfo(trimSingleQuote(fieldList.get(10)));

        return true;
    }

    private String trimSingleQuote(String field) {
        if(field.length() >= 2 && field.startsWith("'") && field.endsWith(",")){
            return field.substring(1,field.length() - 1);
        }
        return field;
    }
}
